// // https://github.com/electron/i18n/tree/master/content/zh-CN/docs

const { app, BrowserWindow, dialog } = require('electron')
const path = require('path')
const url = require('url')
const fs = require('fs');

function getConfigFilePath() {
    const dir = path.join(app.getPath("appData"), "mygameengine");
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }
    const configFilepath = path.join(dir, 'app.json');
    if (!fs.existsSync(configFilepath)) {
        fs.writeFileSync(configFilepath, '{}', 'utf-8');
    }
    return configFilepath;

}

function openEditorWindow(gameUrl) {
    // Create the browser window.
    win = new BrowserWindow({ width: 1600, height: 900 })
    const editorURL = "file://" + __dirname + "/editor/index.html?gameURL=" + encodeURIComponent(gameUrl);
    console.log(editorURL)
    win.loadURL(editorURL)
    win.openDevTools();
}

function openSelectProjectWindow(callback) {
    dialog.showOpenDialog({
        title: "请选择一个游戏文件夹!",
        properties: ["openDirectory"]
    }, (dirs) => {
        if (!dirs) {
            dialog.showMessageBox({ message: "由于您没有选择文件夹，本游戏引擎即将关闭" })
            app.exit();
        }
        else {
            callback(dirs[0])
        }
    });
}

function onSelectProject(gameURL) {
    if (fs.existsSync(gameURL + "/project.json")) {
        const data = { gameUrl: gameURL };
        fs.writeFileSync(configFilepath, JSON.stringify(data, null, '\t', 'utf-8'));
        openEditorWindow(gameURL);
    }
    else {
        dialog.showMessageBox({ message: "请选择一个游戏文件夹" })
        openSelectProjectWindow(onSelectProject)
    }
}

const configFilepath = getConfigFilePath();

function initEditor() {


    const content = fs.readFileSync(configFilepath, 'utf-8');

    const config = JSON.parse(content);

    const gameUrl = config.gameUrl;

    if (gameUrl) {
        openEditorWindow(gameUrl);

        // openEditorWindow("E:\\GameEngine\\test\\MyGame\\runtime");
    }
    else {
        openSelectProjectWindow(onSelectProject);
    }
}

app.on('ready', initEditor)




// const { app, BrowserWindow } = require('electron')
// const path = require('path')
// const url = require('url')

// function createWindow() {
//     // Create the browser window.
//     win = new BrowserWindow({ width: 1600, height: 900 })

//     // 然后加载应用的 index.html。
//     win.loadURL(url.format({
//         //  pathname: path.join(__dirname, 'editor/index.html'),
//         pathname: path.join(__dirname, 'runtime/index.html'),
//         protocol: 'file:',
//         slashes: true
//     }))
//     win.openDevTools();
// }

// app.on('ready', createWindow)